library("dplyr")
library("ggplot2")
library("plotly")


bdate <- as.Date("2021-05-21", tryFormats = c("%Y-%m-%d"))

wtdt <- read.csv("wt.csv") %>%
  mutate(
    date = as.Date(date, tryFormats = c("<%Y-%m-%d")),
    ddur = date - bdate,
    wdur2 = as.numeric(ddur) / 7,
    wdur = difftime(date, bdate, units = "week")
  )

wtdtstat <- wtdt %>%
  mutate(
    ma3 = stats::filter(Weight, filter = rep(1/3, 3), sides = 1),
    ma5 = stats::filter(Weight, filter = rep(1/5, 5), sides = 1),
    ma7 = stats::filter(Weight, filter = rep(1/7, 7), sides = 1),
    md3 = zoo::rollmedian(Weight, k = 3, fill = NA, align = "right"),
    md5 = zoo::rollmedian(Weight, k = 5, fill = NA, align = "right"),
    md7 = zoo::rollmedian(Weight, k = 7, fill = NA, align = "right")
    ## mma3 = unlist(slider::slide(Weight, mean, .before = 3-1)),
    ## mma5 = unlist(slider::slide(Weight, mean, .before = 5-1)),
    ## mma7 = unlist(slider::slide(Weight, mean, .before = 7-1)),
  ) %>%
  tidyr::pivot_longer(c(Weight, starts_with("ma"), starts_with("md")),
                      names_to = "stat", names_prefix = NULL, names_sep = NULL,
                      values_to = "value", values_drop_na = FALSE) %>%
  mutate(stat = factor(stat),
         stat = dplyr::recode(stat,
                              Weight = "Weight Line",
                              ma3 = "3 Day Moving Average",
                              ma5 = "5 Day Moving Average",
                              ma7 = "7 Day Moving Average",
                              md3 = "3 Day Meian",
                              md5 = "5 Day Meian",
                              md7 = "7 Day Meian",
                              ))


g <- ggplot(wtdtstat, aes(x = wdur, y = value)) +
  geom_line(aes(group = stat, color = stat)) +
  geom_point(data = wtdt, aes(x = wdur, y = Weight)) +
  ## geom_line(aes(x = wdur, y = ma5)) +
  # coord_flip() + # Rotate the box plot
  labs(x = "", y = "")

plotly_p <- ggplotly(g)
plotly_p



wtdt <- read.csv("https://gitee.com/shuguangS/wt/raw/master/wt.csv")
